package com.xwder.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

/**
 * 1. SimpleChannelInboundHandler 是 ChannelInboundHandlerAdapter <p>
 * 2. HttpObject 客户端和服务器端相互通讯的数据被封装成 HttpObject <p>
 *
 * @author xwder
 * @date 2021/3/23 09:25
 **/
public class HttpServerHandler extends SimpleChannelInboundHandler {

    private static final Logger logger = LoggerFactory.getLogger(HttpServerHandler.class);

    /**
     * 读取客户端发送的数据
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        logger.info("获取channel:{},pipeline:{},通过pipeline获取的channnel:{},当前ctx的handler:{}",
                ctx.channel(), ctx.pipeline(), ctx.pipeline().channel(), ctx.handler());

        //判断 msg 是不是 HttpRequest 请求
        if (msg instanceof HttpRequest) {
            logger.info("ctx类型:{}", ctx.getClass());
            logger.info("pipeline hashcode:{},HttpServerHandler hashCode:{}", ctx.pipeline().hashCode(), this.hashCode());
            logger.info("msg类型:{},客户端地址:{}", msg.getClass(), ctx.channel().remoteAddress().toString().substring(1));

            HttpRequest httpRequest = (HttpRequest) msg;
            // 获取 uri
            URI uri = new URI(httpRequest.uri());
            // 获取uri, 过滤指定的资源
            if ("/favicon.ico".equals(uri.getPath())) {
                logger.info("请求了 favicon.ico, 不做响应");
                return;
            }

            // 回复信息给浏览器 [http协议]
            ByteBuf byteBuf = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_16);
            // 构造一个http的相应，即 httpResponse
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);

            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());

            // 将构建好 response返回
            ctx.writeAndFlush(response);

        }
    }
}
